<template>
  <div class="xtx-tabs">
    <nav>
      <a
        href="javascript:;"
        v-for="item in slotArr"
        :key="item.id"
        :class="{ active: item.props.name === modelValue }"
        @click="switchName(item.props.name)"
      >
        {{ item.props.label }}
      </a>
    </nav>
    <!-- 强制加key进行更新 -->
    <component :is="activeComponent" :key="activeComponent.props.name"/>
  </div>
</template>

<script>
import { computed, ref } from 'vue'
export default {
  name: 'XtxTabs',
  props: {
    modelValue: {
      type: String
    }
  },
  setup (props, { emit, slots }) {
    const slotArr = ref([])
    // 动态生成时,slots.default()执行结果不一致bug修复
    // 处理动静问题
    slots.default().forEach(slot => {
      if (slot.type.name === 'XtxTabsPanel') {
        slotArr.value.push(slot)
      } else {
        slotArr.value = [...slotArr.value, ...slot.children]
      }
    })

    function switchName (name) {
      emit('update:modelValue', name)
    }
    const activeComponent = computed(() => {
      let com = null
      slotArr.value.forEach(slot => {
        if (slot.props.name === props.modelValue) {
          com = slot
        }
      })
      return com
    })
    return {
      switchName, activeComponent, slotArr
    }
  }
}
</script>
<style lang="scss">
.xtx-tabs {
  background: #fff;
  > nav {
    height: 60px;
    line-height: 60px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;
    > a {
      width: 110px;
      border-right: 1px solid #f5f5f5;
      text-align: center;
      font-size: 16px;
      &.active {
        border-top: 2px solid $xtxColor;
        height: 60px;
        background: #fff;
        line-height: 56px;
      }
    }
  }
}
</style>
